package com.library.mapper;

import com.library.entity.BorrowRecord;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface BorrowMapper {
    @Insert("INSERT INTO borrow_record(book_id, user_id, borrow_date, return_date, status) " +
            "VALUES(#{bookId}, #{userId}, #{borrowDate}, #{returnDate}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(BorrowRecord record);
    
    @Update("UPDATE borrow_record SET status=#{status}, actual_return_date=#{actualReturnDate}, " +
            "overdue_fee=#{overdueFee} WHERE id=#{id}")
    int update(BorrowRecord record);
    
    @Select("SELECT br.*, b.name as book_name, u.username as user_name " +
            "FROM borrow_record br " +
            "LEFT JOIN book b ON br.book_id = b.id " +
            "LEFT JOIN user u ON br.user_id = u.id " +
            "WHERE br.user_id = #{userId}")
    @Results({
        @Result(property = "bookName", column = "book_name"),
        @Result(property = "userName", column = "user_name")
    })
    List<BorrowRecord> findByUserId(Integer userId);
    
    @Select("SELECT br.*, b.name as book_name, u.username as user_name " +
            "FROM borrow_record br " +
            "LEFT JOIN book b ON br.book_id = b.id " +
            "LEFT JOIN user u ON br.user_id = u.id")
    @Results({
        @Result(property = "bookName", column = "book_name"),
        @Result(property = "userName", column = "user_name")
    })
    List<BorrowRecord> findAll();
    
    @Select("SELECT * FROM borrow_record WHERE id = #{id}")
    BorrowRecord findById(Integer id);
    
    @Select("SELECT COUNT(*) FROM borrow_record " +
            "WHERE user_id = #{userId} AND book_id = #{bookId} AND status = 0")
    int findUnreturnedBook(Integer userId, Integer bookId);
} 